import LmMessage from "./index.vue"
let instances = []
let verticalTop = 16
let index = 0
export default {
    install(Vue) {
        function generateInstance(options) {
            const Ctor = Vue.extend(LmMessage)
            let instance = new Ctor({
                propsData: options
            }).$mount(document.createElement('div'))
            instance.verticalTop = computedVerVerticalTop()

            instance.id = `message-${index++}`

            instance.$once("close", () => {
                updateVerticalTop(instance)
            })
              return instance
        }

        // 获取我们生成的每一个message的top
        function computedVerVerticalTop() {
            return instances.reduce((acc, cul) => {
                return cul.$el.offsetHeight + acc + verticalTop
            }, verticalTop)
        }
        // 更新verticalTop
        function updateVerticalTop(instance) {

            let removeTop = instance.verticalTop

            let removeIndex = instances.findIndex(item => {
                return item.id === instance.id
            })
            instances.splice(removeIndex, 1)
            for (let i = removeIndex; i < instances.length; i++) {
                let curTop = instances[i].verticalTop
                instances[i].verticalTop = removeTop
                removeTop = curTop
            }

        }
        Vue.prototype.$message = function (options) {
            let instance = generateInstance(options)
            instances.push(instance)
        }
    }
}